# coding: utf-8

from flask import Blueprint
from flask import url_for
from flask import render_template
from flask import request
from flask import redirect
from flask import session
from leancloud import Object, Query

from tools import logging

agm_view = Blueprint('agm', __name__)

TAGID = '563ac7d360b2c0a27d84cfdc'

@agm_view.route('/')
@logging.agmlog
def index():
    items = [
        {'title': u'关于音速风暴', 'link': '#'},
        {'title': u'产品推荐', 'link': url_for('agm.productitems')},
        {'title': u'产品功能及特点介绍', 'link': '#'},
        {'title': u'联系我们', 'link': url_for('agm.contact')},
        ]
    return render_template('agm0.1/agm_item.html', title=u'音速风暴', items=items)
    

@agm_view.route('/productitems')
@logging.agmlog
def productitems():
    # items = [
        # {'title': u'模拟系列', 'link': url_for('agm.productitem')},
        # {'title': u'数码系列', 'link': '#'},
        # ]
    tags = Query(Object.extend('Cache_list')).get(TAGID).get('content')
    items = []
    for i, item in enumerate(tags):
        items.append({'title': item, 'link': url_for('agm.productitem', bid=i+1)})
    return render_template('agm0.1/agm_item.html', title=u'产品推荐', items=items)
    

@agm_view.route('/productitem')
@logging.agmlog
def productitem():
    # items = [
        # {'name': 'TR-01CN', 'link': url_for('agm.product')}
    # ]
    bigtosmall = lambda x: x.replace('BigPic', 'SmallPic').replace('.jpg', 's.jpg')
    bid = request.args.get('bid')
    if bid and bid.isdigit():
        bid = int(bid)
        items = []
        tags = Query(Object.extend('Cache_list')).get(TAGID).get('content')
        query = Query(Object.extend('Agm_Product'))
        tag = tags[bid-1]
        query.equal_to('tag', tag)
        items = query.find()
    else:
        items = []
        tag = u''
    return render_template('agm0.1/agm_productlist.html', title=tag, items=items, bigtosmall=bigtosmall)
    
@agm_view.route('/product')
@logging.agmlog
def product():
    # items = [
        # {'name': 'TR-01CN', 'price': 399, 'jf': 12, 'img': '/static/images/TR-01CN.jpg',
        # 'img_td': '/static/images/TR-01CNtedian.jpg', 'img_pz': '/static/images/TR-01CNpeizhi.jpg'}
    # ]
    # item = items[0]
    pid = request.args.get('pid')
    if pid:
        item = Query(Object.extend('Agm_Product')).get(pid)
    else:
        item = {}
    return render_template('agm0.1/agm_product.html', item=item)
    
@agm_view.route('/contact')
@logging.agmlog
def contact():
    return render_template('agm0.1/agm_contact.html', title=u'联系我们')
    
@agm_view.route('/auth')
def auth():
    code = request.args.get('code')
    from tools.wechatAPI import getauth
    openid = getauth(code)
    query = Query(Object.extend('WechatUser'))
    query.equal_to('openid', openid)
    try:
        userid = query.first().id
        session['wechatuserid'] = userid
    except:
        pass
    return redirect(url_for('agm.index'))    